
import {renderToString,renderToNodeStream} from 'react-dom/server'
import express from 'express'
import React from 'react'
import {Provider} from 'react-redux'
import  {createStore,applyMiddleware,compose} from 'redux'
import thunk from 'redux-thunk'
import {StaticRouter as Router} from 'react-router-dom'
import  reducers from '../src/reducer'//合并reducer
import csshook from 'css-modules-require-hook/preset' // import hook before routes
import staticPath from '../build/asset-manifest.json'

import assetHook from 'asset-require-hook'
assetHook({
    extensions: ['jpg', 'png', 'gif', 'webp'],
    limit: 8000
})
// require('asset-require-hook')({
//     extensions: ['jpg', 'png', 'gif', 'webp'],
//     limit: 8000
// })
import App from '../src/app'
// const express=require('express')
const userRouter=require('./user')
const bodyParser=require('body-parser')
const cookieParser=require('cookie-parser')
const app=express()
const server=require('http').Server(app)
const io=require('socket.io')(server)
const model=require('./module')
const Chat=model.getModels('chat')
const User=model.getModels('user')
const path=require('path')

// function App(){
//     return (
//         <div>
//             <p>server render</p>
//         </div>
//     )
// }

//work with express
io.on('connection',function (socket) {
    //这里要用socket.on socket是当前这次链接的请求
    socket.on('sendMsg',function (data) {
        // console.log(data);
        const {from,to,msg,avatar}=data
        const chatid=[from,to].sort().join('')
        let msg_from='';
        let msg_to='';
        // console.log(from,to)
        // console.log(from);
        //这里查出来每一条消息的谁发的 发给谁的
        User.find({'$or':[{_id:from},{_id:to}]},(err,doc)=>{
            if(!err){
                doc.forEach(v=>{
                    v.id==from?msg_from=v.user:msg_to=v.user
                })
                // msg_from=doc.user;
                
                // User.find({_id:to},(e,d)=>{
                    // if(!e){
                        // to_name=d.user;
                        // console.log(doc)
                        // msg_from=doc[0].user;
                        // msg_to=doc[1].user;
                       
                        Chat.create({chatid,from,to,avatar,msg_from,msg_to,content:msg,},(err,doc)=>{
                            if(!err){
                                io.emit('recvMsg',Object.assign({},doc._doc))
                            }
                           
                        })
                    // }
                // })
            }
        })
        
        // io.emit('recvMsg',data)
        
    })
    
})

app.use(cookieParser())
app.use(bodyParser.json())
app.use('/user',userRouter)
app.use(function(req,res,next){
    if (req.url === '/favicon.ico') return;
    if(req.url.startsWith('/user/')||req.url.startsWith('/static')){
        return next()
    }

    const store =createStore(reducers,compose(applyMiddleware(thunk)
    ))
    const context={}

    const htmlResouse=renderToString((<Provider store={store} >
        <Router location={req.url} context={context}>
            <App></App></Router></Provider>))
    const KeywordsObj={
        '/boss':'boss牛人列表',
        '/msg':'消息列表'
    }
    res.write(`<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="theme-color" content="#000000">
        <link rel="shortcut icon" href="/favicon.ico">
        <meta name="description" content="react ssr redux 聊天">
        <meta name="Keywords" content="${KeywordsObj[req.url]}">
        <link rel="stylesheet" href="/${staticPath['main.css']}">
        
        <title>React App</title>
    </head>
    <body>
        <noscript>
        You need to enable JavaScript to run this app.
        </noscript>
        <div id="root">
    `)
    const markeyStream=renderToNodeStream((<Provider store={store} >
        <Router location={req.url} context={context}>
            <App></App></Router></Provider>))
    markeyStream.pipe(res,{end:false})
    markeyStream.on('end',()=>{
        res.write(`</div>
        </body>
        <script src='/${staticPath['main.js']}'></script>  
        </html>`)
        res.end()
    })
    const page=`
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="theme-color" content="#000000">
        <link rel="shortcut icon" href="/favicon.ico">
        <meta name="description" content="react ssr redux 聊天">
        <meta name="Keywords" content="${KeywordsObj[req.url]}">
        <link rel="stylesheet" href="/${staticPath['main.css']}">
        
        <title>React App</title>
    </head>
    <body>
        <noscript>
        You need to enable JavaScript to run this app.
        </noscript>
        <div id="root">${htmlResouse}</div>
    </body>
    <script src='/${staticPath['main.js']}'></script>  
    </html>`

    
    // res.send(page)
    // console.log('resolve=============='+path.resolve('/a','/b','c'))
    // return res.sendFile(path.resolve('build/index.html'))
})

app.use('/',express.static(path.resolve('build')))
server.listen(9093,function () {
    console.log('node start----')
})



